package com.yzk.aigy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzk.aigy.common.Result;
import com.yzk.aigy.model.system.SysUser;
import com.yzk.aigy.model.vo.AssginRoleVo;
import com.yzk.aigy.model.vo.SysUserQueryVo;
import com.yzk.aigy.service.SysRoleService;
import com.yzk.aigy.service.SysUserService;
import com.yzk.aigy.utils.MD5Helper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户管理")
@RequiredArgsConstructor
@RequestMapping("/admin/system/sysUser")
public class SysUserController {

    private final SysUserService sysUserService;

    @ApiOperation("用户分页查询")
    @PostMapping("/page")
    public Result<IPage<SysUser>> findRoleByPageQuery(@RequestBody SysUserQueryVo sysUserQueryVo) {
        return Result.ok(sysUserService.page(sysUserQueryVo));
    }

    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public Result<Object> addUser(@RequestBody SysUser sysUser) {
        // 通过MD5 工具类加密
        String passwordWithMD5 = MD5Helper.encrypt(sysUser.getPassword());
        // 将加密密码设置给sysUser
        sysUser.setPassword(passwordWithMD5);
        return sysUserService.save(sysUser) ? Result.ok() : Result.fail();
    }

    @ApiOperation("根据ID查询用户")
    @GetMapping("/findUserById/{id}")
    public Result<SysUser> findUserById(@PathVariable Long id) {
        return Result.ok(sysUserService.getById(id));
    }

    @ApiOperation("修改用户")
    @PostMapping("/updateUser")
    public Result<Object> updateUser(@RequestBody SysUser sysUser) {
        return sysUserService.updateById(sysUser) ? Result.ok() : Result.fail();
    }

    @ApiOperation("根据ID删除用户")
    @DeleteMapping("/removeById/{id}")
    public Result<Object> removeUserById(@PathVariable Long id) {
        return sysUserService.removeById(id) ? Result.ok() : Result.fail();
    }

    @ApiOperation("批量删除用户")
    @DeleteMapping("/removeBatchUserByIds")
    public Result<Object> removeBatchUserByIds(@RequestBody List<Long> ids) {
        return sysUserService.removeByIds(ids) ? Result.ok() : Result.fail();
    }

    @ApiOperation("更改用户状态")
    @GetMapping("/updateStatus/{id}/{status}")
    public Result<Object> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        sysUserService.update(Wrappers.<SysUser>lambdaUpdate().set(SysUser::getStatus, status).eq(SysUser::getId, id));
        return Result.ok();
    }

}
